package com.atguigu.tingshu.order.service.impl;

import com.atguigu.tingshu.model.order.LocalMsg;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.mapper.LocalMsgMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.MqOpsService;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author codingyz
 * @Description
 * @date 2025/3/28 21:17
 * @Version 1.0
 */
@Service
@Slf4j
public class MqOpsServiceImpl implements MqOpsService {

    @Autowired
    private LocalMsgMapper localMsgMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void updateLocalMsgStatus(String content) {
        LocalMsg localMsg = localMsgMapper.selectOne(new LambdaQueryWrapper<LocalMsg>().eq(LocalMsg::getMsgContent, content));
        if (localMsg != null) {
            localMsg.setStatus(1);
            localMsgMapper.updateById(localMsg);
        }
    }

    @Override
    public void cancelOrder(String orderNo) {
        int count = orderInfoMapper.cancelOrder(orderNo);
        log.info("订单取消{}，订单号：{}", count == 0 ? "失败" : "成功", orderNo);
    }

    @Override
    public void wxPaySuccess(String orderNo) {
        OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderNo(orderNo);
        Long userId = orderInfo.getUserId();
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        BeanUtils.copyProperties(orderInfo, orderInfoVo);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderInfo.getId()));
        List<OrderDetailVo> orderDetailVos = orderDetails.stream().map(orderDetail -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            BeanUtils.copyProperties(orderDetail, orderDetailVo);
            return orderDetailVo;
        }).toList();
        orderInfoVo.setTradeNo(orderNo);
        orderInfoVo.setOrderDetailVoList(orderDetailVos);
        orderInfoService.paySuccess(orderInfoVo, userId, orderNo);
    }
}
